<?php

namespace app\api\controller\wash;


use app\common\controller\Api;
use app\common\model\User;
use app\common\model\wash\Order as WashOrder;
use think\Db;

/**
 * 清洗订单
 */
class Order extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['detail', 'payok'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // protected $auth = ['test3'];

    /**
     * 订单结算页
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="shop_id", type="int", required=true, description="门店")
     * @ApiParams (name="goods_id", type="int", required=false, description="商品ID")
     * @ApiParams (name="num", type="int", required=false, description="商品数量")
     * @ApiParams (name="cart_ids", type="json", required=false, description="购物车IDS")
     * @ApiParams (name="send_type", type="str", required=true, description="配送方式:1=上门取送,2=自送到店")
     * @ApiParams (name="is_urgent", type="int", required=true, description="是否加急:0=否,1=是")
     * @ApiParams (name="use_credit", type="int", required=true,sample="0", description="使用积分数量")
     * @ApiParams (name="coupon_id", type="int", sample="0", required=false, description="优惠券")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function preorder()
    {
        try {
            $user = User::get($this->auth->id);
            $goods_info = [];
            $data = $this->request->put();
            $res = WashOrder::getOrderPriceInfo(
                $user,
                $this->request->post('goods_id'),
                $this->request->post('num'),
                $data['cart_ids'] ?? '',
                $this->request->post('send_type'),
                $this->request->post('is_urgent'),
                $this->request->post('coupon_id'),
                $this->request->post('shop_id'),
            );

            $res['money'] = $user->commission;
            $res['score'] = $user->score;
            $res['credit_fee'] = 0;
            if ($this->request->post('use_credit')) {
                $res['credit_fee'] = sprintf("%.2f",  $this->request->post('use_credit') / config('site.integral_ratio'), 2);
                if ($res['credit_fee'] > $res['total_fee']) {
                    $res['credit_fee'] = $res['total_fee'];
                    $res['use_credit'] = $res['total_fee'] * config('site.integral_ratio');
                } else {
                    $res['use_credit'] = $this->request->post('use_credit');
                }
            }
        } catch (\Exception $e) {
            $this->responseMsg(1, '', $e->getMessage());
        }


        $this->responseMsg(0, $res);
    }

    /**
     * 提交订单
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="shop_id", type="int", required=true, description="门店")
     * @ApiParams (name="address_id", type="int", required=false, description="地址")
     * @ApiParams (name="coupon_id", type="int", sample="0", required=false, description="优惠券")
     * @ApiParams (name="goods_id", type="int", required=false, description="商品ID")
     * @ApiParams (name="num", type="int", required=false, description="商品数量")
     * @ApiParams (name="cart_ids", type="json", required=false, description="购物车IDS")
     * @ApiParams (name="pay_type", type="str", required=true,sample="wxpay", description="支付方式:wxpay=微信,money=余额")
     * @ApiParams (name="use_credit", type="int", required=true,sample="0", description="使用积分数量")
     * @ApiParams (name="send_type", type="str", required=true, description="配送方式:1=上门取送,2=自送到店")
     * @ApiParams (name="is_urgent", type="int", required=true, description="是否加急:0=否,1=是")
     * @ApiParams (name="apply_time", type="str", required=true,sample="2023-05-11 10:12:00", description="交付时间")
     * @ApiParams (name="remark", type="str", required=false, description="备注")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function addorder()
    {
        $user = $this->auth->getUser();
        $rej = $this->validate(
            $this->request->post(),
            [
                'shop_id'  => 'require|gt:0',
                // 'address_id'  => 'require|gt:0',
                'pay_type' => 'require|in:wxpay,money',
                'send_type' => 'require|in:1,2',
                'is_urgent' => 'require|in:0,1',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }

        $data = $this->request->put();

        $res = WashOrder::createOrder(
            $user,
            $this->request->post('shop_id'),
            $this->request->post('address_id'),
            $this->request->post('pay_type'),
            $this->request->post('send_type'),
            $this->request->post('is_urgent'),
            $this->request->post('apply_time'),

            $this->request->post('coupon_id'),
            $this->request->post('use_credit'),
            $this->request->post('goods_id'),
            $this->request->post('num'),
            $data['cart_ids'] ?? '',
            $this->request->post('remark'),

        );

        $this->responseObj($res);
    }





    /**
     * 我的订单列表
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="status", type="str", required=true, description="状态:1=待交付,2=清洗中,3=待取送,4=已完成")
     * @ApiParams (name="page", type="int", required=false, description="页码")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':'0','msg':'返回成功'})
     */
    public function mylist()
    {
        $user = $this->auth->getUser();
        if ($this->request->post('status') === '') {
            $res = WashOrder::with(['shop' => function ($q) {
                $q->withField('id,nickname,avatar');
            }, 'goods'])
                ->where('fa_wash_order.user_id', $user->id)
                ->where('fa_wash_order.status', 'not in', ['0', '-1'])
                ->order('fa_wash_order.id desc')->paginate(10);
        } else {
            $res = WashOrder::with(['shop' => function ($q) {
                $q->withField('id,nickname,avatar');
            }, 'goods'])
                ->where('fa_wash_order.user_id', $user->id)
                ->where('fa_wash_order.status', strval($this->request->post('status')))
                ->order('fa_wash_order.id desc')->paginate(10);
        }

        $this->responseMsg(0, $res);
    }





    /**
     * 订单详情
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, description="订单id")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function detail()
    {

        $rej = $this->validate(
            $this->request->post(),
            [
                'id'  => 'require|gt:0',
            ]
        );

        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $res = WashOrder::with(['shop' => function ($q) {
            $q->withField('id,nickname,avatar,address,mobile');
        }, 'user' => function ($q) {
            $q->withField('id,nickname,avatar');
        }, 'goods'])
            ->where('fa_wash_order.id', $this->request->post('id'))->find();
        if (!$res) {
            $this->responseMsg(1007, '', '没有找到数据');
        }

        $this->responseMsg(0, $res->toArray());
    }


    /**
     * 重新支付
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="core_id", type="integer", required=true, sample="", description="core_id")
     * @ApiParams (name="pay_type", type="str", required=true,sample="wxpay", description="支付方式:money=余额")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function repay()
    {
        $user = $this->auth->getUser();
        $rej = $this->validate(
            $this->request->post(),
            [
                'core_id'  => 'require|gt:0',
                // 'address_id'  => 'require|gt:0',
                'pay_type' => 'require|in:wxpay,money',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }

        // $data = $this->request->put();

        $res = WashOrder::repay(
            $user,
            $this->request->post('core_id'),
            $this->request->post('pay_type'),
        );

        $this->responseObj($res);
    }


    private function checkShopAuth($user)
    {
        if ($user->role == 'shop') {
            $shop_id = $user->id;
        }
        if ($user->role == 'rider') {
            if (!$user->shop_id) {
                $this->responseMsg(1006, '', '没有门店');
            }
            $shop_id = $user->shop_id;
        }
        if (!isset($shop_id)) {
            $this->responseMsg(1006, '', '没有门店权限');
        }
        return $shop_id;
    }

    /**
     * 取消订单
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function cancel()
    {
        $user = $this->auth->getUser();

        $rej = $this->validate(
            $this->request->post(),
            [
                'id'  => 'require|number',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $order = WashOrder::where('id', $this->request->post('id'))->find();
        if (!$order) {
            $this->responseMsg(1007, '', '没有找到数据');
        }
        $res = WashOrder::cancel($order);
        $this->responseObj($res);
    }


    public function payok()
    {

        $rej = $this->validate(
            $this->request->post(),
            [
                'id'  => 'require|number',
            ]
        );

        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $res = WashOrder::payok($this->request->get('id'));

        $this->responseMsg(0);
    }
}
